package cn.tramy.pinxian.wind.eventstore.storage

import cn.tramy.pinxian.wind.eventstore.query.entry.DomainEventEntry
import reactor.core.publisher.Flux
import reactor.core.publisher.toFlux

class MemEventStorage : EventStorage {
    private val eventCache: MutableMap<String, MutableList<DomainEventEntry>> = mutableMapOf()
    override fun persistent(eventEntry: DomainEventEntry) {
        val key = this.buildKey(eventEntry)
        val events = this.eventCache.getOrPut(key, { mutableListOf<DomainEventEntry>() })
        events.add(eventEntry)
    }


    override fun readEventEntry(aggregateId: String, aggregateType: String): Flux<DomainEventEntry> =
            this.eventCache["${aggregateId}_$aggregateType"]?.toFlux() ?: Flux.empty()


    private fun buildKey(eventEntry: DomainEventEntry) = "${eventEntry.aggregateId}_${eventEntry.aggregateType}"
}